package main

import (
	"fmt"
	"io/ioutil"
	"os"
	"os/exec"
	"peilian-api/app/global/config"
	"peilian-api/app/global/databases/tables"
	"peilian-api/app/global/variable"
	_ "peilian-api/bootstrap"
	"peilian-api/utils/sdk"
	"strings"
	"time"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

func InitMySQL() (*gorm.DB, error) {
	dsn := fmt.Sprintf(
		"%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local&timeout=%s",
		variable.Config.Mysql.UserName,
		variable.Config.Mysql.PassWord,
		variable.Config.Mysql.Host,
		variable.Config.Mysql.Port,
		variable.Config.Mysql.DBName,
		variable.Config.Mysql.TimeOut,
	)
	DB, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger:                                   logger.Default.LogMode(logger.Info),
		DisableForeignKeyConstraintWhenMigrating: true,
	})
	if err != nil {
		return nil, err
	}
	sqlDB, _ := DB.DB()
	//设置数据库连接池参数
	sqlDB.SetMaxOpenConns(100) //设置数据库连接池最大连接数
	sqlDB.SetMaxIdleConns(20)  //连接池最大允许的空闲连接数，如果没有sql任务需要执行的连接数大于20，超过的连接会被连接池关闭。
	return DB, nil
}

// 批量转pcm -> mp3
func main() {
	config.InitConfig("/Users/a123/Desktop/go/peilian-api/config/config.yaml")

	fmt.Print(variable.Config.Mysql.UserName)
	db, _ := InitMySQL()
	st := []tables.RealQues{}
	// db.Model(&tables.Session{}).Where("status = 1 and school != '北京工商大学'").Find(&st)
	// fmt.Print(variable.Config.Mysql.UserName)
	// for i := 0; i < len(st); i++ {
	// 	// updates := make(map[string]interface{})
	// 	// updates["total_score"] = rand.Intn(65) + 30
	// 	// db.Model(&tables.Session{}).Where("id= ?", st[i].ID).Updates(updates)
	// 	// fmt.Println(rand.Intn(65) + 30)

	// 	res, _ := http.Post("http://127.0.0.1/practice/session/9877/report", "application/json;charset=utf-8", bytes.NewBuffer([]byte{}))
	// 	defer res.Body.Close()
	// }
	db.Model(&tables.RealQues{}).Where("id = 15388").Find(&st)
	for i := 0; i < len(st); i++ {
		if len(st[i].AnswerAudio) == 0 {
			continue
		}
		pcmUrl := st[i].AnswerAudio
		pcmUrl = strings.Replace(pcmUrl, ".pcm", ".mp3", -1)
		s := strings.Split(pcmUrl, "/")
		pcmName := s[4:]

		p := variable.Config.UfsInfo.UfsUrl + st[i].AnswerAudio
		out := pcmName[0]
		fmt.Println(pcmName)
		cmdArguments := []string{"-y", "-ac", "1", "-ar", "16000", "-f", "s16le", "-i", p, "-c:a", "libmp3lame", "-q:a", "2", out}

		c := exec.Command("ffmpeg", cmdArguments...)
		c.Run()

		dateTime := time.Now().Format("2006-01-02")
		fileName := fmt.Sprintf("%s/static/mp3/%s/%s", variable.Config.UfsInfo.BucketPrefix, dateTime, pcmName[0])
		b, _ := ioutil.ReadFile(out)
		if err := sdk.IOput(b, fileName, "audio/mpeg"); err != nil {
			fmt.Println("失败")
		}
		// 更新数据
		db.Model(&tables.RealQues{}).Where("id = ?", st[i].ID).Updates(map[string]interface{}{"audio": variable.Config.UfsInfo.UfsUrl + fileName})
		os.Remove(out)
	}

}
